// 实现这个项目的构建任务
const { src, dest, watch, parallel, series } = require('gulp')
const gulp_clean = require('gulp-clean')
const sass = require('gulp-sass')
const cleanCss = require('gulp-clean-css')
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const swig = require('gulp-swig')
const imagemin = require('gulp-imagemin')
const browserSync = require('browser-sync').create()

const opts = {
  data: {
    menus: [
      {
        name: 'Home',
        icon: 'aperture',
        link: 'index.html',
      },
      {
        name: 'About',
        link: 'about.html',
      },
      {
        name: 'Contact',
        link: '#',
        children: [
          {
            name: 'Weibo',
            link: ''
          },
          {
            name: 'Twitter',
            link: ''
          },
          {
            name: 'divider',
          },
          {
            name: 'About',
            link: ''
          },
        ]
      },
    ],
    pkg: require('./package.json'),
    date: new Date()
  }
}

const clean = () => {
  return src('dist', {read: false, allowEmpty: true})
          .pipe(gulp_clean({force: true}))
}

const styles = () => {
  return src('./src/assets/styles/*.scss', { base: 'src' })
          .pipe(sass())
          .pipe(cleanCss())
          .pipe(dest('dist'))
}

const scripts = () => {
  return src('./src/assets/scripts/*.js', { base: 'src' })
          .pipe(babel({
            presets: ['@babel/env']
          }))
          .pipe(uglify())
          .pipe(dest('dist'))
}

const html = () => {
  return src('./src/**/**.html', { base: 'src' })
          .pipe(swig(opts))
          .pipe(dest('dist'))
}

const image = () => {
  return src('src/assets/images/*', { base: 'src' })
          .pipe(imagemin())
          .pipe(dest('dist'))
}

const extra = () => {
  return src('src/assets/fonts/*', { base: 'src' })
          // .pipe(imagemin())
          .pipe(dest('dist'))
}

const server = () => {
  browserSync.init({
    server: {
      baseDir: "./dist"
    }
  });
}

const compile = parallel(html, styles, scripts)

const build = series(clean, parallel(compile, image, extra))

const start = series(build, server)

// TODO
const lint = () => {}

//TODO
const deploy = () => {}

module.exports = {
  clean,
  serve,
  lint,
  build,
  start,
  deploy,
}